/*
 * @Author: qingyuanyang
 * @Date: 2023-09-21 13:48:50
 * @LastEditors: qingyuanyang
 * @LastEditTime: 2023-10-11 15:09:23
 * @FilePath: /utilization-platform/src/pages/VisualizationAnalysis/InstrumentSetting/index.tsx
 * @Description: 仪器设置
 */
import React, { useState, useEffect } from 'react';
import Table from '@/components/table';
import style from './index.module.scss';
import { ColumnsType } from 'antd/es/table';
import {
  Button,
  Divider,
  Form,
  Input,
  InputNumber,
  message,
  Radio,
  Switch,
} from 'antd';
import Icon from '@/components/SvgIcon';
import { useDebounceFn, useRequest } from 'ahooks';
import DefaultModal from '@/components/modal';
import {
  deleteInstrument,
  EditInstrument,
  getInstrumentList,
  InstrumentDetails,
  InstrumentResponse,
} from '@/api/deviceInstrument';
import useModal from '@/hooks/useModal';
import Ellipsis from '@/components/ellipsis-text';
const InstrumentSetting: React.FC = () => {
  const [modal, contextHolder] = useModal();
  const [data, setData] = useState<InstrumentResponse>([]);
  const [params, setParams] = useState<InstrumentDetails>({
    page: 1,
    pageSize: 10,
  });
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const [id, setId] = useState(-99);
  const [btnLoading, setBtnLoading] = useState<boolean>(false);
  const [switchLoading, setSwitchLoading] = useState<boolean>(false);

  useEffect(() => {
    getList();
  }, [params]);

  const columns: ColumnsType<InstrumentDetails> = [
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      key: 'deviceType',
      width: 280,
      render: value => <Ellipsis content={value} />,
    },
    {
      title: '利用率计算基数(h)',
      dataIndex: 'utilizationDenominator',
      key: 'utilizationDenominator',
      // width: 155,
      align: 'center',
    },
    {
      title: '计划利用率(%)',
      dataIndex: 'plannedUtilization',
      key: 'plannedUtilization',
      // width: 155,
      render: value => value && value * 100,
      align: 'center',
    },
    {
      title: '利用率高阈值(%)',
      dataIndex: 'utilizationHighThreshold',
      key: 'utilizationHighThreshold',
      // width: 155,
      render: value => value && value * 100,
      align: 'center',
    },
    {
      title: '利用率低阈值(%)',
      dataIndex: 'utilizationLowThreshold',
      key: 'utilizationLowThreshold',
      // width: 155,
      render: value => value && value * 100,
      align: 'center',
    },
    {
      title: '是否开启有效利用率',
      dataIndex: 'statusSegmentationEnable',
      key: 'statusSegmentationEnable',
      // width: 155,
      align: 'center',
      render: (value, record: InstrumentDetails) => (
        <Switch
          checkedChildren="ON"
          unCheckedChildren="OFF"
          checked={value === 1}
          onChange={e => onSwitchChange(e, record)}
          loading={id === record.id ? switchLoading : false}
          className={style.switchDiv}
          size="small"
        />
      ),
    },
    {
      title: '操作',
      dataIndex: 'operate',
      width: 100,
      render: (_, record: InstrumentDetails) => (
        <div className={style.operate}>
          <a onClick={() => updateDevice(record)}>编辑</a>
          <Divider
            type="vertical"
            style={{ height: 14, borderInlineStartColor: '#DCDEE0' }}
          />
          <a onClick={() => deleteDevice(record)}>删除</a>
        </div>
      ),
    },
  ];

  const suffixSpan = (text: string) => {
    return <span className={style.suffix}>{text}</span>;
  };

  const { loading, refresh: getList } = useRequest(
    () => getInstrumentList(params),
    {
      onSuccess: ({ data }) => {
        setData(data);
      },
      onError: err => {
        console.log(err);
      },
    }
  );
  //是否开启有效利用率
  const onSwitchChange = (e: boolean, record: InstrumentDetails) => {
    setId(record.id || -99);

    const {
      deviceType,
      utilizationDenominator,
      plannedUtilization,
      utilizationHighThreshold,
      utilizationLowThreshold,
      id,
    } = record;
    setSwitchLoading(true);
    EditInstrument({
      deviceType,
      utilizationDenominator,
      plannedUtilization,
      utilizationHighThreshold,
      utilizationLowThreshold,
      id,
      statusSegmentationEnable: e ? 1 : 0,
    }).then(res => {
      try {
        if (res.data) {
          setSwitchLoading(false);
          getList();
          setId(-99);
        }
      } catch (error) {
        setSwitchLoading(false);
        console.log(error);
        setId(-99);
      }
    });
  };

  //关键字搜索
  const { run: handleChange } = useDebounceFn(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = e.target?.value?.trim();
      setParams({ searchKey: value, page: 1 });
    },
    { wait: 300 }
  );
  //添加
  const onAdd = () => {
    form.setFieldsValue({
      utilizationDenominator: 24,
      utilizationHighThreshold: 80,
      utilizationLowThreshold: 30,
      statusSegmentationEnable: 0,
    });
    setBtnLoading(false);
    setOpen(true);
    setId(-99);
  };

  const onCancel = () => {
    setOpen(false);
    form.resetFields();
  };
  //添加成功
  const onOk = () => {
    form.validateFields().then(async () => {
      setBtnLoading(true);
      const obj = form.getFieldsValue();

      const data = id === -99 ? obj : { ...obj, id };
      const isSuccess = await EditInstrument(data);
      if (isSuccess) {
        getList();
        setOpen(false);
        form.resetFields();
        message.success(`${id === -99 ? '添加' : '编辑'}成功`);
      }
      setBtnLoading(false);
    });
  };
  //编辑设备
  const updateDevice = (record: InstrumentDetails) => {
    setBtnLoading(false);
    setId(record.id || -99);
    setOpen(true);
    const {
      utilizationHighThreshold,
      utilizationLowThreshold,
      plannedUtilization,
    } = record;
    form.setFieldsValue({
      ...record,
      plannedUtilization: plannedUtilization && plannedUtilization * 100,
      utilizationHighThreshold:
        utilizationHighThreshold && utilizationHighThreshold * 100,
      utilizationLowThreshold:
        utilizationLowThreshold && utilizationLowThreshold * 100,
    });
  };
  //删除设备
  const deleteDevice = (record: InstrumentDetails) => {
    modal.warning({
      width: 360,
      title: '确认要删除该设备类吗？',
      content: `删除设备类型【${record.deviceType}】后，将无法恢复`,
      okText: '删除',
      onOk: () => {
        deleteInstrument({
          id: record.id,
        }).then(res => {
          if (res.data) {
            message.success('删除成功');
            getList();
          }
        });
      },
    });
  };

  //切换page
  const onPageChange = (pagination: any) => {
    const { current, pageSize } = pagination;
    setParams({ ...params, page: current, pageSize });
  };
  const onStatusChange = (val: any) => {
    const value = val.target.value;
    form.setFieldValue('statusSegmentationEnable', value);
  };
  //当前页面ref
  const divRef = React.useRef<HTMLDivElement | null>(null);

  //输入整数校验
  const numberRules: Record<string, { message: string; pattern: RegExp }> = {
    number: {
      message: '请输入整数',
      pattern: /^([0]|[1-9][0-9]*)$/,
    },
  };

  return (
    <div className={style.instrumentDiv} ref={r => (divRef.current = r)}>
      <div className={style.header}>
        <Input
          style={{ width: 240 }}
          prefix={<Icon name="icon-search" className={style.iconStyle} />}
          placeholder="请输入关键字进行查询"
          onChange={handleChange}
          allowClear
        />
        <Button type="primary" onClick={onAdd}>
          新增设备类
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={data.records || []}
        loading={loading}
        onChange={onPageChange}
        scroll={{ y: 'calc(100vh - 335px)' }}
        pagination={
          (data?.total || 0) > 10
            ? {
                current: data.page,
                pageSize: data.pageSize,
                total: data.total,
                showTotal: total => `共${total}条`,
                showSizeChanger: true,
                showQuickJumper: true,
              }
            : false
        }
      />
      <DefaultModal
        open={open}
        onCancel={onCancel}
        onOk={onOk}
        title={id === -99 ? '新增设备类' : '编辑设备类'}
        okText="保存"
        okButtonProps={{ loading: btnLoading }}
        getContainer={divRef.current || false}
        width={560}>
        <Form
          form={form}
          labelCol={{ span: 7 }}
          layout="horizontal"
          labelAlign="right"
          colon={false}>
          <Form.Item
            name="deviceType"
            label="设备类型"
            rules={[{ required: true, message: '请输入设备类型' }]}>
            <Input placeholder="请输入" disabled={id === -99 ? false : true} />
          </Form.Item>
          <Form.Item
            name="utilizationDenominator"
            label="利用率计算基数"
            rules={[
              { required: true, message: '请输入利用率计算基数' },
              numberRules.number,
            ]}>
            <InputNumber
              min={0}
              max={24}
              placeholder="请输入"
              suffix={suffixSpan('小时')}
              style={{ width: 106 }}
            />
          </Form.Item>
          <Form.Item
            name="plannedUtilization"
            label="计划利用率"
            rules={[numberRules.number]}>
            <InputNumber
              min={0}
              max={100}
              placeholder="请输入"
              suffix={suffixSpan('%')}
              style={{ width: 106 }}
            />
          </Form.Item>
          <Form.Item
            name="utilizationHighThreshold"
            label="利用率高阈值"
            rules={[
              { required: true, message: '请输入利用率高阈值' },
              numberRules.number,
            ]}>
            <InputNumber
              min={0}
              max={100}
              placeholder="请输入"
              suffix={suffixSpan('%')}
              style={{ width: 106 }}
            />
          </Form.Item>
          <Form.Item
            name="utilizationLowThreshold"
            label="利用率低阈值"
            rules={[
              { required: true, message: '请输入利用率低阈值' },
              numberRules.number,
            ]}>
            <InputNumber
              min={0}
              max={100}
              placeholder="请输入"
              suffix={suffixSpan('%')}
              style={{ width: 106 }}
            />
          </Form.Item>
          <Form.Item
            name="statusSegmentationEnable"
            label="是否开启有效利用率"
            style={{ marginBottom: 0 }}
            rules={[{ required: true, message: '请选择是否开启有效利用率' }]}>
            <Radio.Group
              defaultValue={btnLoading ? null : 0}
              onChange={onStatusChange}>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </DefaultModal>
      {contextHolder}
    </div>
  );
};

export default InstrumentSetting;
